package com.wingy.myhandlerdemo2;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class myHandlerDemo2Activity extends AppCompatActivity {

    private ProgressBar bar = null;
    private Button startButton = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_handler_demo2);

        bar = (ProgressBar) findViewById(R.id.bar);
        startButton = (Button) findViewById(R.id.button);

        startButton.setOnClickListener(new ButtonListener());

    }

    Handler updateBarHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            bar.setProgress(msg.arg1);
            updateBarHandler.post(updateThread);
        }
    };

    class ButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {

            bar.setVisibility(View.VISIBLE);
            updateBarHandler.post(updateThread);
        }
    }

    Runnable updateThread = new Runnable() {
        int i = 0;
        @Override
        public void run() {
            System.out.println("Begin Thread");
            i += 10;
            Message message = updateBarHandler.obtainMessage();

            message.arg1 = i;

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            updateBarHandler.sendMessage(message);

            if(i == 100) {
                updateBarHandler.removeCallbacks(updateThread);
            }
        }
    };
}
